const express = require('express')
const bodyParser = require('body-parser')
const expressJWT = require('express-jwt')

const admin = require('./router/admin')
const mms = require('./router/mms')
const home = require('./router/home')
const tokenFn = require('./tools/token')
const until = require('./until/until')

const app = express()
const port = 8000

//验证token是否过期并规定哪些路由不用验证
app.use(
  expressJWT({
    secret: 'mes_qdhd_mobile_xhykjyxgs',
    algorithms: ['HS256'],
  }).unless({
    path: ['/admin/captcha', '/admin/login'], //除了这个地址，其他的URL都需要验证
  })
)

// 解析token获取用户信息
app.use(function (req, res, next) {
  var token = req.headers['authorization']
  if (token == undefined) {
    return next()
  } else {
    tokenFn
      .verToken(token)
      .then((data) => {
        req.data = data
        return next()
      })
      .catch((error) => {
        return next()
      })
  }
})

//当token失效返回提示信息
app.use(function (err, req, res, next) {
  if (err.status == 401) {
    return res.json(until.formatter(401, '暂未登录或者token失效'))
  }
})

app.all('*', (req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'content-type,Authorization')
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
  res.header('Content-Type', 'application/json;charset=utf-8')
  next()
})

app.use(bodyParser.json()) // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true }))

app.use(express.static('asset'))

app.use('/admin', admin)
app.use('/mms', mms)
app.use('/home', home)

app.get('/', (req, res) => {
  res.send('index')
})

app.listen(port, () => {
  console.log('服务已启动。。。')
})
